﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Pub;
using Pub.Tools;

namespace Pub.Controls.MastForm
{
    public partial class BaseFrm : Form
    {
        public BaseFrm()
        {
            InitializeComponent();
        }

        [Category("Define")]
        public virtual void actFormLoad()
        {
            this.toolStrip1.ImageList = imgLoad;
            this.tsbAdd.Image = imgLoad.Images[1];
            this.tsbEdit.Image = imgLoad.Images[2];
            this.tsbDelete.Image = imgLoad.Images[3];
            this.tsbSave.Image = imgLoad.Images[4];
            this.tsbCancel.Image = imgLoad.Images[5];
            this.tsbRefresh.Image = imgLoad.Images[6];
            this.tsbOut.Image = imgLoad.Images[7];
            this.tsbQuit.Image = imgLoad.Images[0];
            this.timerShow.Enabled = true;
            this.gridEx1.ReadOnly = true;
        }

        public enum TableFieldEnum
        {
            UserCode,
            UserName
        }

        private TableFieldEnum tfEnum = TableFieldEnum.UserName;

        [Category("Define")]
        public TableFieldEnum TFEnum
        {
            get { return tfEnum; }
            set { this.tfEnum = value; }
        }

        private string[] dbFields;

        [Category("Define")]
        public string[] DBFields
        {
            get { return dbFields; }
            set { this.dbFields = value; }
        }

        private string deleteMsgField;

        [Category("Define")]
        public string DeleteMsgField
        {
            get { return deleteMsgField; }
            set { this.deleteMsgField = value; }
        }

        [Category("Define")]
        public virtual void actAdd()
        {
            this.bsdt.AddNew();
            this.gridEx1.ReadOnly = false;
        }

        [Category("Define")]
        public virtual void actEdit()
        {
            this.gridEx1.ReadOnly = false;
        }


        [Category("Define")]
        public virtual void actDelete()
        {
            if (this.dtEx1.DataTable.Rows.Count == 0) { return; }

            if (this.gridEx1.SelectedRows.Count == 0)
            {
                if (this.gridEx1.CurrentRow == null)
                {
                    MsgTools.ErrorMsg("删除失败!请先选中行后再执行.");
                    return;
                }

                int index = this.gridEx1.CurrentRow.Index;    //取得选中行的索引 

                string DeleteMsg = "";

                if ((DeleteMsgField != null) && (DeleteMsgField != string.Empty))
                {
                    DeleteMsg = " [" + this.gridEx1.Rows[index].Cells[DeleteMsgField].Value.ToString() + "] ";
                }
                //单选删除
                if (!MsgTools.QuestionMsg("确定删除当前记录" + DeleteMsg + "?")) { return; }
                this.bsdt.RemoveCurrent();
            }
            else
            {
                //多选删除
                int[] iSelect = new int[this.gridEx1.SelectedRows.Count];
                string[] DeleteMsg = new string[this.gridEx1.SelectedRows.Count];

                for (int i = 0; i < this.gridEx1.SelectedRows.Count; i++)
                {
                    iSelect[i] = this.gridEx1.SelectedRows[i].Index;
                    if ((DeleteMsgField != null) && (DeleteMsgField != string.Empty))
                    {
                        DeleteMsg[i] = this.gridEx1.Rows[iSelect[i]].Cells[DeleteMsgField].Value.ToString();
                    }
                }

                string Msg = string.Empty;

                //组织删除字段信息
                if ((DeleteMsgField != null) && (DeleteMsgField != string.Empty))
                {
                    Array.Reverse(DeleteMsg);
                    int iMsg = Math.Min(DeleteMsg.Length, 5);

                    Msg = string.Join("\r\n", DeleteMsg, 0, iMsg);
                    if (DeleteMsg.Length > 5)
                    {
                        Msg += "\r\n...";
                    }
                }

                if (!MsgTools.QuestionMsg(string.Format("确定删除{0}条记录?\r\n" + Msg, this.gridEx1.SelectedRows.Count))) { return; }

                for (int i = 0; i < iSelect.Length; i++)
                {
                    int k = iSelect[i];
                    if (this.gridEx1.Rows[k].Selected)
                    {
                        this.bsdt.RemoveAt(k);
                    }
                }

            }
            
        }

        [Category("Define")]
        public virtual void actSave()
        {
            try
            {
                this.gridEx1.EndEdit();
                this.bsdt.EndEdit();
            }
            catch (Exception ex)
            {
                MsgTools.ErrorMsg(ex.Message.ToString());
            }
            if (this.dtEx1.DataTable.GetChanges() != null)
            {
                if (dtEx1.Save)
                {
                    MsgTools.InfoMsg("数据提交成功!");
                    this.dtEx1.DataTable.AcceptChanges();
                }
                else
                {
                    //删除失败,刷新数据
                    MsgTools.InfoMsg("数据提交失败,系统将刷新数据!");
                    actRefresh();
                }
            }
        }

        [Category("Define")]
        public virtual void actCancel()
        {
            if (MsgTools.QuestionMsg("取消提交数据?"))
            {
                try
                {
                    this.gridEx1.CancelEdit();
                    this.bsdt.CancelEdit();
                }
                catch
                {
                }
                if (this.dtEx1.DataTable.GetChanges() != null)
                {
                    this.dtEx1.DataTable.RejectChanges();
                }
            }
        }

        [Category("Define")]
        public virtual void actRefresh()
        {
         //   if (DesignMode) { return; }
            this.dtEx1.DataBinds();
            this.bsdt.DataSource = this.dtEx1.DataTable;
            this.gridEx1.DataSource = this.bsdt;

            if (this.dtEx1.DataTable == null)
            {
                MsgTools.InfoMsg("数据加载失败,请[退出]或稍后[刷新].");
                return;
            }

            this.gridEx1.AutoGenerateColumns = true;
            Pub.Tools.GridTools.ReadGVStyle(this, this.gridEx1);
            ShowGridColumns();

        }

        [Category("Define")]
        public virtual void actExportToExcel()
        {
            ExportToXML();
        }

        private void ExportToXML()
        {
            string filter = AutoFilterColumnHeaderCell.GetFilterStatus(this.gridEx1);
            DataTable dt = DBClass.SelectDB(this.dtEx1.DataTable, filter);
            GridTools.ExportToXml(this.gridEx1, dt);
        }


        [Category("Define")]
        public virtual void actQuit()
        {
            Pub.Tools.GridTools.SaveDGVStyle(this, this.gridEx1);

            this.Close();
        }


        private void FrmBase_Load(object sender, EventArgs e)
        {
            actFormLoad();
        }



        private void timerShow_Tick(object sender, EventArgs e)
        {
            this.timerShow.Enabled = false;
            //执行刷新动作
            actRefresh();
        }


        private void tsbAdd_Click(object sender, EventArgs e)
        {
            actAdd();
        }

        private void tsbEdit_Click(object sender, EventArgs e)
        {
            actEdit();
        }

 
        private void tsbDelete_Click(object sender, EventArgs e)
        {
            actDelete();
        }

        private void tsbRefresh_Click(object sender, EventArgs e)
        {
            actRefresh();
        }

        private void tsbSave_Click(object sender, EventArgs e)
        {
            actSave();

        }

        private void tsbCancel_Click(object sender, EventArgs e)
        {
            actCancel();
        }

        private void tsbOut_Click(object sender, EventArgs e)
        {
            actExportToExcel();
        }

        private void tsbQuit_Click(object sender, EventArgs e)
        {
            actQuit();
        }


        private void dtEx1_OnNewRow(object sender, DataTableNewRowEventArgs e)
        {
            if (e.Row.Table.Columns.Contains("cCreate"))
            {
                string cCreate = string.Empty;
                switch (this.tfEnum)
                {
                    case TableFieldEnum.UserCode:
                        {
                            cCreate = PubVar.NowUser.cUserCode;
                            break;
                        }
                    case TableFieldEnum.UserName:
                        {
                            cCreate = PubVar.NowUser.cUserName;
                            break;
                        }
                }
                e.Row["cCreate"] = cCreate;
            }

            if (e.Row.Table.Columns.Contains("dCreate"))
            {
                e.Row["dCreate"] = System.DateTime.Now;
            }
            
        }

        private void ShowGridColumns()
        {
            string ss = string.Join("", dbFields, 0, dbFields.Length);
            if (ss == string.Empty) { return; }
            for (int i = 0; i < this.gridEx1.ColumnCount; i++)
            {
                this.gridEx1.Columns[i].Visible = false;
            }
            for (int i = 0; i < this.dbFields.Length; i++)
            {
                string[] strArray = System.Text.RegularExpressions.Regex.Split(dbFields[i], @"[,]+");
                string strdb = strArray[0].Trim();
                string strText = strdb;
                string strFormat = "L";

                if (strArray.Length > 1)
                {
                    strText = strArray[1].Trim();
                }
                if (strArray.Length > 2)
                {
                    strFormat = strArray[2].Trim();
                }

                Boolean bl = this.gridEx1.Columns.Contains(strdb);
                if (bl)
                {
                    this.gridEx1.Columns[strdb].Visible = bl;
                    this.gridEx1.Columns[strdb].HeaderText = strText;
                    switch (strFormat.ToUpper())
                    { 
                        case "C":
                            {
                                this.gridEx1.Columns[strdb].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                                break;
                            }
                        case "L":
                            {
                                this.gridEx1.Columns[strdb].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
                                break;
                            }
                        case "R":
                            {
                                this.gridEx1.Columns[strdb].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                                break;
                            }
                    }

                }
            }
        }

        private void gridEx1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            String filterStatus = Pub.Controls.AutoFilterColumnHeaderCell.GetFilterStatusText(this.gridEx1);
            if (String.IsNullOrEmpty(filterStatus))
            {

                btnShowALL.Visible = false;
                tslMess.Visible = false;
            }
            else
            {
                btnShowALL.Visible = true;
                tslMess.Visible = true;
                tslMess.Text = filterStatus;
            }
        }

        private void btnShowALL_Click(object sender, EventArgs e)
        {
            Pub.Controls.AutoFilterColumnHeaderCell.RemoveFilter(this.gridEx1);
        }









    }
}
